package com.feihong.yw189.bluetooth.contral;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.Base64;
import android.widget.Toast;

import com.djlm.reader.device.ReaderController;
import com.djlm.reader.inter.DJLMReaderCallBack;
import com.djlm.reader.model.CardInfo;
import com.feihong.yw189.R;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.activity.SearchBlueActivity;
import com.feihong.yw189.bluetooth.bean.Data;
import com.feihong.yw189.bluetooth.bean.GetIpInfo;
import com.feihong.yw189.bluetooth.bean.IdInfo;
import com.feihong.yw189.bluetooth.bleutils.BleGlobUtils;
import com.feihong.yw189.bluetooth.listener.UpLoadListener;
import com.feihong.yw189.bluetooth.startreadcard.DjlmConnectUtils;
import com.feihong.yw189.bluetooth.startreadcard.HengHongDaConnectUtils;
import com.feihong.yw189.bluetooth.startreadcard.HuaShiConnectUtils;
import com.feihong.yw189.bluetooth.startreadcard.Kt8000ConnectUtils;
import com.feihong.yw189.bluetooth.startreadcard.Kt8003ConnectUtils;
import com.feihong.yw189.bluetooth.startreadcard.SenRuiConnectUtils;
import com.feihong.yw189.bluetooth.startreadcard.ShenSiConnectUtils;
import com.feihong.yw189.bluetooth.startreadcard.XinTongConnectUtils;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.google.gson.Gson;
import com.kaer.sdk.bt.BtReadClient;
import com.kaeridcard.client.BtReaderClient;
import com.kaeridcard.client.IClientCallBack;
import com.kaeridcard.client.IdCardItem;

import org.xutils.common.Callback;

import static com.djlm.reader.device.ReaderController.OPERATE_SUCCESS_KEY;
import static com.kaeridcard.client.BtReaderClient.is_bt_connect;

/**
 * 读卡控制中心
 */

public class ReadContralCenter {
    private BluetoothAdapter ba;
    private Context mContext;
    private SearchBlueActivity activity;
    private int index;
    private BluetoothDevice remoteDevice;
    private Boolean mFlag = false;
    private UpLoadListener mOnUpLoadListener;
    private BtReadClient mBtReadClient;
    private String bluetoothName;
    private String bleName;
    private String bleAddress;

    private HuaShiConnectUtils huaShiConnectUtils;
    private Kt8000ConnectUtils kt8000ConnectUtils;
    private Kt8003ConnectUtils kt8003ConnectUtils;
    private ShenSiConnectUtils shenSiConnectUtils;
    private HengHongDaConnectUtils hengHongDaConnectUtils;
    private DjlmConnectUtils djlmConnectUtils;
    private SenRuiConnectUtils senRuiConnectUtils;
    private BtReaderClient mClient;
    private XinTongConnectUtils xinTongConnectUtils;

    public ReadContralCenter(Context context, BluetoothAdapter ba,
                             BtReadClient mBtReadClient, BluetoothDevice remoteDevice,
                             String bleName, String bleAddress, int index, String bluetoothName,
                             Boolean flag, UpLoadListener mOnUpLoadListener) {
        this.mContext = context;
        this.activity = (SearchBlueActivity) context;
        this.ba = ba;
        this.mBtReadClient = mBtReadClient;
        this.remoteDevice = remoteDevice; // 设备
        this.bleName = bleName; // 蓝牙名称
        this.bleAddress = bleAddress; // 蓝牙地址
        this.index = index; // 蓝牙索引
        this.bluetoothName = bluetoothName; // 蓝牙读卡名称
        this.mFlag = flag; // 需不需要给服务端上传身份证数据
        this.mOnUpLoadListener = mOnUpLoadListener;

    }

    public void disConnect() {

        switch (index) {
            case 0:
                if (huaShiConnectUtils != null) {
                    huaShiConnectUtils.stopConnect();
                }
                break;
            case 1:
                if (kt8000ConnectUtils != null) {
                    kt8000ConnectUtils.stopConnect();
                }
                break;
            case 2:
                if (kt8003ConnectUtils != null) {
                    kt8003ConnectUtils.stopConnect();
                }
                break;
            case 3:
                if (shenSiConnectUtils != null) {
                    shenSiConnectUtils.stopConnect();
                }
                break;
            case 4:
                if (senRuiConnectUtils != null) {
                    senRuiConnectUtils.stopConnect();
                }
                break;
            case 5:
                if (hengHongDaConnectUtils != null) {
                    hengHongDaConnectUtils.stopConnect();
                }
                break;
            case 6:
                if (djlmConnectUtils != null) {
                    djlmConnectUtils.stopConnect();
                }
            case 7:
                if (xinTongConnectUtils != null) {
                    xinTongConnectUtils.stopConnect();
                }
                break;
                default:break;
        }
    }


    public void connectBle() {
        if (index == 4) {
            senRuiConnectUtils = new SenRuiConnectUtils(mContext, remoteDevice, bleName, bleAddress,
                    bluetoothName, mFlag, new UpLoadListener() {
                @Override
                public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                        String nation, String sign_office, String name, String sign_data,
                                        String birth_year, String birth_month, String birth_day, Bitmap photo,
                                        String filePhoto, String idPath, String to, String from, String born,
                                        String photoHeard) {
//                    closeDialog(false, "");

                    mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                            sign_office, name, sign_data, birth_year, birth_month, birth_day,
                            photo, filePhoto, idPath, to,
                            from, born, photoHeard);

                }

                @Override
                public void onErrUpLoad(String err) {
                    closeDialog(true, err);
                }
            });
            senRuiConnectUtils.connect();
        } else if (index == 7) {
            bluetoothName = "信通读卡";
            //                        closeDialog(false, "");
            xinTongConnectUtils = new XinTongConnectUtils(mContext, bleName, bleAddress, bluetoothName, mFlag,
                    new UpLoadListener() {
                        @Override
                        public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                                String nation, String sign_office, String name, String sign_data,
                                                String birth_year, String birth_month, String birth_day,
                                                Bitmap photo, String filePhoto, String idPath, String to,
                                                String from, String born, String photoHeard) {
//                        closeDialog(false, "");
                            mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                                    sign_office, name, sign_data, birth_year, birth_month, birth_day,
                                    photo, filePhoto, idPath, to,
                                    from, born, photoHeard);
                        }

                        @Override
                        public void onErrUpLoad(final String err) {
                            closeDialog(true, err);
                        }
                    });
            xinTongConnectUtils.connect();
        } else {
            new Thread(new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void run() {
                    Looper.prepare();
                    readCardStart();
                }
            }).start();
        }
    }

    private void closeDialog(final boolean isTrue, final String err) {

        if (isTrue) {
            mOnUpLoadListener.onErrUpLoad(err);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void readCardStart() {
        switch (index) {
            case 0: // 华视
                bluetoothName = "华视读卡";
                huaShiConnectUtils = new HuaShiConnectUtils(mContext, ba, remoteDevice,
                        bleName, bleAddress, bluetoothName, mFlag, new UpLoadListener() {
                    @Override
                    public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                            String nation, String sign_office, String name, String sign_data,
                                            String birth_year, String birth_month, String birth_day,
                                            Bitmap photo, String filePhoto, String idPath, String to,
                                            String from, String born, String photoHeard) {
//                        closeDialog(false, "");
                        mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                                sign_office, name, sign_data, birth_year, birth_month, birth_day,
                                photo, filePhoto, idPath, to,
                                from, born, photoHeard);
                    }

                    @Override
                    public void onErrUpLoad(final String err) {
                        closeDialog(true, err);
                    }
                });
                huaShiConnectUtils.connect();
                break;
            case 1: // kt8000
                // 点击扫描之后创建蓝牙对象
                mClient = new BtReaderClient(mContext);
                if (mClient != null) {
                    mClient.setCallBack(mCallback);
                }
                bluetoothName = "卡尔KT8000读卡";
                kt8000ConnectUtils = new Kt8000ConnectUtils(mContext, ba, remoteDevice,
                        bleName, bleAddress, bluetoothName, mFlag, new UpLoadListener() {
                    @Override
                    public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                            String nation, String sign_office, String name, String sign_data,
                                            String birth_year, String birth_month, String birth_day,
                                            Bitmap photo, String filePhoto, String idPath, String to
                            , String from, String born, String photoHeard) {
//                        closeDialog(false, "");
                        mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                                sign_office, name, sign_data, birth_year, birth_month, birth_day,
                                photo, filePhoto, idPath, to,
                                from, born, photoHeard);
                    }

                    @Override
                    public void onErrUpLoad(final String err) {
                        closeDialog(true, err);
                    }
                });

                kt8000ConnectUtils.connect(mClient);
                break;
            case 2: // kt8003
                mClient = new BtReaderClient(mContext);
                if (mClient != null) {
                    mClient.setCallBack(mCallback);
                }
                bluetoothName = "卡尔KT8003读卡";
                kt8003ConnectUtils = new Kt8003ConnectUtils(mContext, mBtReadClient,
                        ba, remoteDevice, bleName, bleAddress, bluetoothName, mFlag,
                        new UpLoadListener() {
                            @Override
                            public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                                    String nation, String sign_office, String name, String sign_data,
                                                    String birth_year, String birth_month, String birth_day,
                                                    Bitmap photo, String filePhoto, String idPath, String to,
                                                    String from, String born, String photoHeard) {
//                                closeDialog(false, "");
                                mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                                        sign_office, name, sign_data, birth_year, birth_month, birth_day,
                                        photo, filePhoto, idPath, to,
                                        from, born, photoHeard);
                            }

                            @Override
                            public void onErrUpLoad(final String err) {
                                closeDialog(true, err);
                            }
                        });

                kt8003ConnectUtils.connect(mClient);


                break;
            case 3: // 神思
                bluetoothName = "神思读卡";
                shenSiConnectUtils = new ShenSiConnectUtils(mContext, ba, remoteDevice,
                        bleName, bleAddress, bluetoothName, mFlag, new UpLoadListener() {
                    @Override
                    public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                            String nation, String sign_office, String name, String sign_data,
                                            String birth_year, String birth_month, String birth_day,
                                            Bitmap photo, String filePhoto, String idPath, String to,
                                            String from, String born, String photoHeard) {
//                        closeDialog(false, "");
                        mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                                sign_office, name, sign_data, birth_year, birth_month, birth_day,
                                photo, filePhoto, idPath, to,
                                from, born, photoHeard);
                    }

                    @Override
                    public void onErrUpLoad(final String err) {
                        closeDialog(true, err);
                    }
                });
                shenSiConnectUtils.connect();

                break;
            case 5: // 恒鸿达
                bluetoothName = "恒鸿达读卡";
                hengHongDaConnectUtils = new HengHongDaConnectUtils(mContext, ba, remoteDevice,
                        bleName, bleAddress, bluetoothName, mFlag, new UpLoadListener() {
                    @Override
                    public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                            String nation, String sign_office, String name, String sign_data,
                                            String birth_year, String birth_month, String birth_day,
                                            Bitmap photo, String filePhoto, String idPath, String to,
                                            String from, String born, String photoHeard) {
//                        closeDialog(false, "");
                        mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                                sign_office, name, sign_data, birth_year, birth_month, birth_day,
                                photo, filePhoto, idPath, to,
                                from, born, photoHeard);
                    }

                    @Override
                    public void onErrUpLoad(final String err) {
                        closeDialog(true, err);

                    }
                });
                hengHongDaConnectUtils.connect();
                break;
            case 6: // 店家联盟
                djlmRead();
                break;
                default:break;
        }
    }

    RequestCallBack<String> upIDCardInfo = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            Gson gson = new Gson();
            IdInfo idInfo = gson.fromJson(result, IdInfo.class);
            int code = idInfo.getStatus();
            String msg = idInfo.getInfo();
            if(code != 1){
                mOnUpLoadListener.onErrUpLoad(msg);
            }else {
                mOnUpLoadListener.onSucUpLoad(bluetoothName,mCardInfo.str_Address,mCardInfo.str_sex,
                        mCardInfo.str_IDCode,mCardInfo.str_Nation,mCardInfo.str_Regorg,mCardInfo.str_name,
                        null,mCardInfo.str_Birth,mCardInfo.str_Birth,mCardInfo.str_Birth,
                        mCardInfo.bitmap_pic,null,null,mCardInfo.str_startDate,mCardInfo.str_endDate,
                        mCardInfo.str_Birth,BleGlobUtils.replaceBlank(
                                BleGlobUtils.bitmapToBase64(mCardInfo.bitmap_pic)));
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            mOnUpLoadListener.onErrUpLoad(mContext.getResources().getString(R.string.connect_sever_error_toast));
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {

        }
    };
    private CardInfo mCardInfo;
    DJLMReaderCallBack readerCallBack = new DJLMReaderCallBack() {
        @Override
        public void operateSuccess(int i, Bundle bundle) {
            mReaderController.closeBluetooth();
            mCardInfo = bundle.getParcelable(OPERATE_SUCCESS_KEY);
            String photoHead = BleGlobUtils.replaceBlank(
                    BleGlobUtils.bitmapToBase64(mCardInfo.bitmap_pic));
            if(mFlag){
                Data dataInfo = new Data();
                dataInfo.setAddress(mCardInfo.str_Address);
                dataInfo.setPhoto(photoHead);
                dataInfo.setSex(mCardInfo.str_sex);
                dataInfo.setIdcardno(mCardInfo.str_IDCode);
                dataInfo.setNation(mCardInfo.str_Nation);
                dataInfo.setGrantdept(mCardInfo.str_Regorg);
                dataInfo.setTo(mCardInfo.str_endDate);
                dataInfo.setForm(mCardInfo.str_startDate);
                dataInfo.setuSAMID("00000");
                dataInfo.setName(mCardInfo.str_name);
                dataInfo.setBorn(mCardInfo.str_Birth);
                Gson gson = new Gson();
                String jsonData = gson.toJson(dataInfo);
                jsonData = Base64.encodeToString(jsonData.getBytes(), Base64.DEFAULT);
                String chuanMa = "{\"reader_name\":\"" + bleName + "\",\"reader_id\":\"" + bleAddress + "\",\"card_reader\":\""+bluetoothName+"\"}";
                App.getApp().getHttpTools().submitCardMsg(chuanMa,jsonData,upIDCardInfo);
            }else {
                mOnUpLoadListener.onSucUpLoad(bluetoothName,mCardInfo.str_Address,mCardInfo.str_sex,
                        mCardInfo.str_IDCode,mCardInfo.str_Nation,mCardInfo.str_Regorg,mCardInfo.str_name,
                        null,mCardInfo.str_Birth,mCardInfo.str_Birth,mCardInfo.str_Birth,
                        mCardInfo.bitmap_pic,null,null,mCardInfo.str_startDate,mCardInfo.str_endDate,
                        mCardInfo.str_Birth,photoHead);
            }
        }

        @Override
        public void operateError(int i, String s) {
            mReaderController.closeBluetooth();
            mOnUpLoadListener.onErrUpLoad(s);
        }
    };
    ReaderController mReaderController;

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void djlmRead() {
        // 点击扫描之后创建蓝牙对象

        mClient = new BtReaderClient(mContext);
        if (mClient != null) {
            mClient.setCallBack(mCallback);
        }

        bluetoothName = "店家联盟读卡";
        App.getApp().getHttpTools().getDJLMIP(new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                GetIpInfo djlmInfo = gson.fromJson(result, GetIpInfo.class);
                if (djlmInfo != null && djlmInfo.getStatus() == 1) {
                    final String url = djlmInfo.getData().getUrl();
                    String ip = djlmInfo.getData().getIp();
                    int endIndex = ip.indexOf(":");
                    String host = ip.substring(0, endIndex);

                    mReaderController = new ReaderController(mContext, readerCallBack, host);
                    mReaderController.readIDCard().setMacAdr(bleAddress).connectBLE();
                } else {
                    mOnUpLoadListener.onErrUpLoad("服务器返回IP地址为空");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                mOnUpLoadListener.onErrUpLoad(mContext.getResources().getString(R.string.connect_sever_error_toast));
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
//        djlmConnectUtils = new DjlmConnectUtils(mContext, ba, remoteDevice,
//                bleName, bleAddress, bluetoothName, mFlag, new UpLoadListener() {
//            @Override
//            public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
//                                    String nation, String sign_office, String name, String sign_data,
//                                    String birth_year, String birth_month, String birth_day,
//                                    Bitmap photo, String filePhoto, String idPath, String to,
//                                    String from, String born, String photoHeard) {
////                        closeDialog(false, "");
//                djlmConnectUtils = null;
//                mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
//                        sign_office, name, sign_data, birth_year, birth_month, birth_day,
//                        photo, filePhoto, idPath, to,
//                        from, born, photoHeard);
//            }
//
//            @Override
//            public void onErrUpLoad(final String err) {
//                djlmConnectUtils = null;
//                closeDialog(true, err);
//            }
//        });
//
//        djlmConnectUtils.connect(mClient, false);
    }

    private int rssi_value;
    private IClientCallBack mCallback = new IClientCallBack() {

        @Override
        public void onBtState(final boolean is_connect) {
            activity.runOnUiThread(new Runnable() {
                public void run() {
                    if (is_connect) {
                        String toast_text = mContext.getString(R.string.bt_connected_ts);
                    } else {
                    }
                    is_bt_connect = is_connect;
                }
            });
        }

        private Handler btHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        if (!is_bt_connect)
                            break;
                        String dis_text;
                        int rssi = rssi_value & 0xff;

                        if ((rssi & 0x80) != 0) {
                            rssi = 0x100 - rssi;
                            dis_text = " -" + rssi;
                        } else if (rssi > 0) {
                            dis_text = " " + rssi;
                        } else
                            dis_text = " 0";
                        String connect_str = mContext.getString(R.string.bt_connected_ts) + "\n" +
                                mContext.getString(R.string.bt_rssi_value) + dis_text;
                        Toast.makeText(mContext, connect_str, Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }
        };

        @Override
        public void onIddataHandle(IdCardItem idCardItem) {
        }
    };
}
